﻿///<copyright>
/// Copyright © 2009 Stephen Styrchak. All Rights Reserved.
///</copyright>
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;

namespace Ferpect.ComponentModel.Design
{
    public class ScreenComponentDesigner : ComponentDesigner
    {
        private IDesignerHost host;
        private ScreenManagerControl parent;
        private Screen screen;
        private DesignScreen screenControl;
        private ISelectionService selectionService;

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.selectionService != null)
                {
                    this.selectionService.SelectionChanged -= this.OnSelectionChanged;
                }
                if (this.parent != null)
                {
                    this.parent.Controls.Remove(this.screenControl);
                    this.screenControl.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);

            this.host = (IDesignerHost)this.GetService(typeof(IDesignerHost));

            this.screen = (Screen)component;
            this.screenControl = new DesignScreen();
            this.screenControl.Text = this.screen.Name;
            this.parent = this.host.RootComponent as ScreenManagerControl;
            if (this.parent != null)
            {
                this.parent.Controls.Add(this.screenControl);
            }
            this.selectionService = (ISelectionService)this.GetService(typeof(ISelectionService));
            this.selectionService.SelectionChanged += this.OnSelectionChanged;
        }

        protected override void PostFilterAttributes(System.Collections.IDictionary attributes)
        {
            base.PostFilterAttributes(attributes);
            DesignTimeVisibleAttribute designTimeVisible = DesignTimeVisibleAttribute.No;
            attributes.Add(typeof(DesignTimeVisibleAttribute), designTimeVisible);
        }

        void OnSelectionChanged(object sender, EventArgs args)
        {
            if (this.selectionService.PrimarySelection == this.Component)
            {
                this.screenControl.Selected = true;
            }
            else
            {
                this.screenControl.Selected = false;
            }
        }

        public bool GetHitTest(Point pt)
        {
            Point clientPt = this.screenControl.PointToClient(pt);
            return this.screenControl.ClientRectangle.Contains(clientPt);
        }
    }
}
